﻿// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Windows.Controls;
using Microsoft.Phone.Controls.Primitives;

namespace Stopwatch.Controls
{
    public class NumbersDataSource : ILoopingSelectorDataSource
    {
        private int minimum = 0;
        private int maximum = 99;
        private int selectedItem = 0;

        public event EventHandler<SelectionChangedEventArgs> SelectionChanged;

        protected virtual void OnSelectedChanged(SelectionChangedEventArgs e)
        {
            var selectionChanged = SelectionChanged;

            if (selectionChanged != null)
                selectionChanged(this, e);

        }

        public object GetNext(object relativeTo)
        {
            var nextValue = int.Parse(relativeTo.ToString()) + 1;

            return (nextValue <= Maximum ? nextValue : Minimum).ToString("D2");
        }

        public object GetPrevious(object relativeTo)
        {
            var previousValue = int.Parse(relativeTo.ToString()) - 1;

            return (previousValue >= Minimum ? previousValue : Maximum).ToString("D2");
        }

        public object SelectedItem
        {
            get
            {
                return selectedItem.ToString("D2");
            }
            set
            {
                var oldValue = selectedItem;
                var newValue = int.Parse(value.ToString());

                if (oldValue == newValue)
                    return;

                selectedItem = newValue;

                OnSelectedChanged(new SelectionChangedEventArgs(new[] { oldValue }, new[] { newValue }));
            }
        }

        public int Minimum
        {
            get
            {
                return minimum;
            }
            set
            {
                minimum = value;

                if (selectedItem < minimum)
                    SelectedItem = value;
            }
        }


        public int Maximum
        {
            get
            {
                return maximum;
            }
            set
            {
                maximum = value;

                if (selectedItem > maximum)
                    SelectedItem = value;
            }
        }
    }
}
